<script lang="ts" setup>
import type { FormInstance, FormRules } from "element-plus"
import type { LoginRequestData } from "./apis/type"
import { removeProjectInfo } from "@/common/utils/cache/local-storage"
import { useSettingsStore } from "@/pinia/stores/settings"
import { getRouters } from '@@/apis/system/menu'
import { usePermissionStore } from "@/pinia/stores/permission"
import { useUserStore } from "@/pinia/stores/user"
import { Lock, User } from "@element-plus/icons-vue"
import { loginApi, registerApi } from "./apis"
import { useFocus } from "./composables/useFocus"

const router = useRouter()

const userStore = useUserStore()

const permissionStore = usePermissionStore()

const { handleBlur, handleFocus } = useFocus()

const isRegister = ref(false)

const isRegisterForm = reactive({
  username: '',
  phonenumber: '',
  email: '',
  password: '',
  twoPassword: ''
})
const validateEmail = (rule: any, value: any, callback: any) => {
  const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
  if (value === '') {
    callback(new Error('请输入邮箱地址'));
  } else if (!emailPattern.test(value)) {
    callback(new Error('请输入正确格式的邮箱'));
  } else {
    callback();
  }
};
const validatePhone = (rule: any, value: any, callback: any) => {
  const phonePattern = /^1[3-9]\d{9}$/;  // 适用于中国大陆手机号
  if (value === '') {

    callback(new Error('请输入手机号'));
  } else if (!phonePattern.test(value)) {
    callback(new Error('请输入正确格式的手机号'));
  } else {
    callback();
  }
};
const validatePasswordConfirm = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请确认密码'));
  } else if (value !== isRegisterForm.password) {
    callback(new Error('两次密码输入不一致'));
  } else {
    callback();
  }
};

const isRegisterFormRules = reactive<FormRules>({
  username: [
    {
      required: true,
      message: "请输入登录名称",
      trigger: "blur",
    },
  ],
  phonenumber: [
    {
      required: true,
      trigger: "blur",
      validator: validatePhone
    },
  ],
  email: [
    {
      required: true,
      trigger: "blur",
      validator: validateEmail
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    { min: 5, max: 16, message: "长度在 5 到 16 个字符", trigger: "blur" }
  ],
  twoPassword: [
    {
      required: true,
      trigger: "blur",
      validator: validatePasswordConfirm
    },
    { min: 5, max: 16, message: "长度在 5 到 16 个字符", trigger: "blur" }
  ]
})
/** 登录表单元素的引用 */
const loginFormRef = ref<FormInstance | null>(null)
const isRegisterFormRef = ref<FormInstance | null>(null)
/** 登录按钮 Loading */
const loading = ref(false)

/** 验证码图片 URL */
const codeUrl = ref("")

/** 登录表单数据 */
const loginFormData: LoginRequestData = reactive({
  username: "admin",
  password: "admin",
  code: ""
})

/** 登录表单校验规则 */
const loginFormRules: FormRules = {
  username: [
    { required: true, message: "请输入登录名称", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 5, max: 16, message: "长度在 5 到 16 个字符", trigger: "blur" }
  ]
}

/** 登录 */
function handleLogin() {
  loginFormRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("表单校验不通过")
      return
    }
    permissionStore.removeChildFlag()
    removeProjectInfo()
    loading.value = true
    loginApi(loginFormData).then(({ data }) => {
      userStore.setToken(data.access_token)
      getRouters().then(res => {
        router.replace("/")

      })
    }).catch(() => {
      loginFormData.password = ""
    }).finally(() => {
      loading.value = false
    })
  })
}
// 注册
function handleRegister() {
  isRegisterFormRef.value?.validate((valid) => {
    if (!valid) {
      ElMessage.error("表单校验不通过")
      return
    }
    registerApi(isRegisterForm).then(({ data }) => {
      ElMessage.success('注册成功,请登录!')
      isRegister.value = !isRegister.value
      isRegisterFormRef.value?.resetFields()
    })
  })
}

</script>

<template>
  <div class="login-container">
    <div class="login-card">
      <!-- <div class="title">
        <img v-if="!isRegister" src="@@/assets/images/login/login-title.png">
        <img v-else src="@@/assets/images/login/register-title.png">
      </div> -->
      <div v-if="!isRegister" class="content">
        <el-form ref="loginFormRef" :model="loginFormData" :rules="loginFormRules" label-position="top"
          @keyup.enter="handleLogin">
          <el-form-item prop="username" label="用户名">
            <el-input v-model.trim="loginFormData.username" placeholder="登录名称" type="text" tabindex="1" size="large">
              <template #prefix>
                <SvgIcon name="username" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password" label="密码">
            <el-input v-model.trim="loginFormData.password" placeholder="密码" type="password" tabindex="2" size="large"
              show-password @blur="handleBlur" @focus="handleFocus">
              <template #prefix>
                <SvgIcon name="password" />
              </template>
            </el-input>
          </el-form-item>
          <el-button :loading="loading" type="primary" size="large" @click.prevent="handleLogin">
            登 录
          </el-button>
          <p @click="isRegister = true" class="register-text">
            没有账号？去<span>注册</span>
          </p>
        </el-form>
      </div>
      <div class="content" v-else>
        <el-form ref="isRegisterFormRef" :model="isRegisterForm" label-width="80px" :rules="isRegisterFormRules"
          autocomplete="off" size="large" @keyup.enter="handleRegister">
          <el-form-item label="登录名称" prop="username">
            <el-input v-model="isRegisterForm.username" autocomplete="new-password" placeholder="请输入用户名"
              class="login-input">
            </el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phonenumber">
            <el-input v-model="isRegisterForm.phonenumber" autocomplete="new-password" placeholder="请输入手机号"
              class="login-input">
            </el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="isRegisterForm.email" autocomplete="new-password" placeholder="请输入邮箱"
              class="login-input">
            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="isRegisterForm.password" show-password autocomplete="new-password" type="password"
              placeholder="请输入密码" class="login-input">
            </el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="twoPassword">
            <el-input v-model="isRegisterForm.twoPassword" show-password autocomplete="new-password" type="password"
              placeholder="请输入确认密码" class="login-input">
            </el-input>
          </el-form-item>
          <el-button :loading="loading" type="primary" size="large" @click.prevent="handleRegister">
            注 册
          </el-button>
          <p @click="isRegister = false" class="register-text">
            已有账号？去<span>登录</span>
          </p>
        </el-form>
      </div>
    </div>
    <div class="login-title" />
  </div>
</template>

<style lang="scss" scoped>
.login-title {
  position: absolute;
  // background: url(@@/assets/images/login/logo1.png);
  background-size: cover;
  width: 300px;
  height: 45px;
  top: 170px;
  left: 70px;
}

.register-text {
  cursor: pointer;
  color: #fff;
  font-size: 14px;
  margin-top: var(--main-padding);
  text-align: center;

  span {
    display: inline-block;
    margin-left: 5px;
    color: #0099ff;
  }
}

.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;    /* 垂直居中 */
  align-items: flex-end;      /* 水平靠右 */
  width: 100%;
  min-height: 100%;
  background: url(@@/assets/images/login/login-bg.png);
  background-size: cover;

  /* 在这里加一个右侧内边距，让内容离右边 200px */
  padding-right: 200px;

  .theme-switch {
    position: fixed;
    top: 5%;
    right: 5%;
    cursor: pointer;
  }

  .login-card {
    width: 480px;
    max-width: 90%;
    background: rgba(255, 255, 255, 0.1);
    overflow: hidden;

    .title {
      display: flex;
      justify-content: center;
      align-items: end;
      height: 125px;
    }

    .content {
      padding: 20px;

      :deep(.el-input.verification) {
        padding: 0;
        overflow: hidden;

        .el-image {
          width: 100px;
          height: 40px;
          border-left: 0px;
          user-select: none;
          cursor: pointer;
          text-align: center;
        }
      }

      .el-button {
        width: 100%;
        margin-top: 10px;
      }
    }
  }
}


:deep(.el-input) {
  --el-input-bg-color: transparent !important;
  --el-input-border-color: rgba(255, 255, 255, 0.2) !important;
  --el-input-hover-border-color: rgba(255, 255, 255, 0.6) !important;
  --el-border-radius-base: 0px;
}

:deep(.el-input.verification) {
  & .el-input__wrapper {
    padding: 1px 1px 1px 15px;
  }

  img {
    height: var(--el-input-inner-height);
    cursor: pointer;
  }
}
</style>
